package com.woniuxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.woniuxy.config.security.component.JwtTokenUtil;
import com.woniuxy.mapper.RoleMapper;
import com.woniuxy.pojo.Admin;
import com.woniuxy.mapper.AdminMapper;
import com.woniuxy.pojo.RespBean;
import com.woniuxy.pojo.Role;
import com.woniuxy.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.utils.AdminUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yuankaiqiang
 * @since 2022-01-28
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RoleMapper roleMapper;
   @Autowired
   @Lazy
   private UserDetailsService userDetailsService;
   @Autowired
   @Lazy
   private PasswordEncoder passwordEncoder;
   @Autowired
   private JwtTokenUtil jwtTokenUtil;

   @Value("${jwt.tokenHead}")
   private String tokenHead;
    /**
     * Description : TODO 登录之后返回token <br/>
     * ChangeLog : 1. 创建 (2022/1/28 23:21 [ykq11]);
     *  @param username
     * @param password
     * @param code
     * @param request
     */
    @Override
    public RespBean login(String username, String password, String code, HttpServletRequest request) {
        String captcha = (String) request.getSession().getAttribute("captcha");
        System.out.println(captcha);
        if(StringUtils.isEmpty(code)||!captcha.equalsIgnoreCase(code)){
            return RespBean.error("验证码输入错误，请重新输入");
        }
        //登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (null == userDetails||!passwordEncoder.matches(password,userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确");
        }
        if(!userDetails.isEnabled()){
            return RespBean.error("账户被禁用，请联系管理员");
        }
        //更新security登录用户对象，userDetails.getAuthorities()权限列表
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userDetails,null,userDetails.getAuthorities());
             SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        //生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = new HashMap<>();
         tokenMap.put("token", token);
         tokenMap.put("tokenHead",tokenHead);
         return RespBean.success("登录成功",tokenMap);
    }

    /**
     * Description : TODO  根据用户名获取用户<br/>
     * ChangeLog : 1. 创建 (2022/1/28 23:45 [ykq11]);
     * @param username *  @return null
     *   //健壮性判断还没写。返回结果可能为空
     */

    @Override
    public Admin getAdminByUsername(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("username",username).eq("enabled",true));
    }
    /**
     * Description : TODO 根据用户id查询角色列表  <br/>
     * ChangeLog : 1. 创建 (2022/2/1 22:33 [ykq11]);
     ** @param  adminId
     * *  @return null
     */
    @Override
    public List<Role> getRoles(Integer adminId) {
        return roleMapper.getRoles(adminId);
    }

    /**
     * Description : TODO  用户头像更新<br/>
     * ChangeLog : 1. 创建 (2022/2/22 20:32 [ykq11]);
     * * @param url
     *
     * @param id
     * @param authentication
     * @return com.woniuxy.pojo.RespBean
     **/
    @Override
    public RespBean updateAdminUserFace(String url, Integer id, Authentication authentication) {
        Admin admin = adminMapper.selectById(id);
        admin.setUserFace(url);
        int result = adminMapper.updateById(admin);
        if(1==result){
            Admin principal =(Admin) authentication.getPrincipal();
            principal.setUserFace(url);
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken
                    (admin,null,authentication.getAuthorities()));
            return RespBean.success("更新成功",url);
        }
        return RespBean.error("更新失败！");
    }

    /**
     * Description : TODO  更新用户密码<br/>
     * ChangeLog : 1. 创建 (2022/2/22 23:23 [ykq11]);
     ** @param oldPass
     * @param pass
     * @param adminId
     * @return com.woniuxy.pojo.RespBean
     **/
    @Override
    public RespBean updateAdminPassword(String oldPass, String pass, Integer adminId) {
        Admin admin = adminMapper.selectById(adminId);
              BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
              //判断旧密码是否正确
              if(encoder.matches(oldPass,admin.getPassword())){
                  admin.setPassword(encoder.encode(pass));
                  int result = adminMapper.updateById(admin);
                  if(1==result){
                      return RespBean.success("更新成功！");
                  }
              }
        return RespBean.error("更新失败！");
    }

    /**
     * Description : TODO  获取所有操作员<br/>
     * ChangeLog : 1. 创建 (2022/2/25 15:42 [ykq11]);
     ** @param keywords
     * @return java.util.List<com.woniuxy.pojo.Admin>
     **/
    @Override
    public List<Admin> getAdminList(String keywords) {
        return adminMapper.getAdminList(AdminUtils.getCurrentAdmin().getId(),keywords);
    }
}
